package org.jeecg.modules.veterans.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.util.*;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.veterans.entity.SysVeteransCard;
import org.jeecg.modules.veterans.entity.SysVeterans;
import org.jeecg.modules.veterans.vo.SysVeteransPage;
import org.jeecg.modules.veterans.service.ISysVeteransService;
import org.jeecg.modules.veterans.service.ISysVeteransCardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 退役军人信息表
 * @Author: jeecg-boot
 * @Date:   2022-03-27
 * @Version: V1.0
 */
@Api(tags="退役军人信息表")
@RestController
@RequestMapping("/veterans/sysVeterans")
@Slf4j
public class SysVeteransController {
	@Autowired
	private ISysVeteransService sysVeteransService;
	@Autowired
	private ISysVeteransCardService sysVeteransCardService;
	 @Autowired
	 public ISysUserService sysUserService;
	 @Autowired
	 public ISysUserService sysUserRoleService;
	 @Autowired
	 private ISysUserDepartService sysUserDepartService;
	 @Autowired
	 private RedisUtil redisUtil;
	/**
	 * 分页列表查询
	 *
	 * @param sysVeterans
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@RequiresPermissions("service:view")
	//@AutoLog(value = "退役军人信息表-分页列表查询")
	@ApiOperation(value="退役军人信息表-分页列表查询", notes="退役军人信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<SysVeterans>> queryPageList(SysVeterans sysVeterans,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SysVeterans> queryWrapper = QueryGenerator.initQueryWrapper(sysVeterans, req.getParameterMap());
		Page<SysVeterans> page = new Page<SysVeterans>(pageNo, pageSize);
		IPage<SysVeterans> pageList = sysVeteransService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param sysVeteransPage
	 * @return
	 */
	@AutoLog(value = "退役军人信息表-添加")
	@ApiOperation(value="退役军人信息表-添加", notes="退役军人信息表-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody SysVeteransPage sysVeteransPage) {
		SysVeterans sysVeterans = new SysVeterans();
		BeanUtils.copyProperties(sysVeteransPage, sysVeterans);
		sysVeteransService.saveMain(sysVeterans, sysVeteransPage.getSysVeteransCardList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param sysVeteransPage
	 * @return
	 */
	@AutoLog(value = "退役军人信息表-编辑")
	@ApiOperation(value="退役军人信息表-编辑", notes="退役军人信息表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody SysVeteransPage sysVeteransPage) {
		SysVeterans sysVeterans = new SysVeterans();
		BeanUtils.copyProperties(sysVeteransPage, sysVeterans);
		SysVeterans sysVeteransEntity = sysVeteransService.getById(sysVeterans.getId());
		if(sysVeteransEntity==null) {
			return Result.error("未找到对应数据");
		}
		sysVeteransService.updateMain(sysVeterans, sysVeteransPage.getSysVeteransCardList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "退役军人信息表-通过id删除")
	@ApiOperation(value="退役军人信息表-通过id删除", notes="退役军人信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		sysVeteransService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "退役军人信息表-批量删除")
	@ApiOperation(value="退役军人信息表-批量删除", notes="退役军人信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.sysVeteransService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "退役军人信息表-通过id查询")
	@ApiOperation(value="退役军人信息表-通过id查询", notes="退役军人信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<SysVeterans> queryById(@RequestParam(name="id",required=true) String id) {
		SysVeterans sysVeterans = sysVeteransService.getById(id);
		if(sysVeterans==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(sysVeterans);

	}

	 /**
	  * 通过phone查询
	  *
	  * @param phone
	  * @return
	  */
	 //@AutoLog(value = "退役军人信息表-通过id查询")
	 @ApiOperation(value="退役军人信息表-通过phone查询", notes="退役军人信息表-通过id查询")
	 @GetMapping(value = "/queryByPhone")
	 public Result<SysVeterans> queryByPhone(@RequestParam(name="phone",required=true) String phone) {
		 SysVeterans sysVeterans = sysVeteransService.selectVeteransByPhone(phone);
		 return Result.OK(sysVeterans);
	 }

	 /**
	  * 优抚对象身份认证
	  *
	  * @param phone
	  * @param phone
	  * @param phone
	  * @param phone
	  * @param phone
	  * @return
	  */
	 //@AutoLog(value = "退役军人身份认证")
	 @ApiOperation(value="退役军人身份认证", notes="退役军人身份认证")
	 @GetMapping(value = "/identity")
	 public Result identity(@RequestParam(name="name",required=true) String name,
									 @RequestParam(name="sfzh",required=true) String sfzh,
									 @RequestParam(name="inputCode",required=true) String inputCode,
									 @RequestParam(name="checkKey",required=true) String checkKey) {
		 if(inputCode==null){
			 return Result.error("验证码无效");
		 }
		 String lowerCaseCaptcha = inputCode.toLowerCase();
		 String realKey = Md5Util.md5Encode(lowerCaseCaptcha+checkKey, "utf-8");
		 Object checkCode = redisUtil.get(realKey);
		 //当进入登录页时，有一定几率出现验证码错误 #1714
		 if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
			 log.warn("验证码错误，key= {} , Ui checkCode= {}, Redis checkCode = {}", checkKey, lowerCaseCaptcha, checkCode);
			 return Result.error("验证码错误");
		 }

		 SysVeterans sysVeterans = sysVeteransService.selectVeteransBySfzh(sfzh);
		 if(sysVeterans != null && name.equals(sysVeterans.getName())){
		 	 sysVeterans.setStatus("2");
		 	 //更新user
			 SysUser user = sysUserService.getUserByUserNum(sysVeterans.getSfzh());
			 sysUserService.updateById(user.setVeteransId(sysVeterans.getId()));
		 	 sysVeteransService.updateById(sysVeterans);
			 return Result.OK("认证成功！");
		 }else {
			 return Result.error("认证失败！");
		 }
	 }
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "电子优待证信息表通过主表ID查询")
	@ApiOperation(value="电子优待证信息表主表ID查询", notes="电子优待证信息表-通主表ID查询")
	@GetMapping(value = "/querySysVeteransCardByMainId")
	public Result<List<SysVeteransCard>> querySysVeteransCardListByMainId(@RequestParam(name="id",required=true) String id) {
		List<SysVeteransCard> sysVeteransCardList = sysVeteransCardService.selectByMainId(id);
		return Result.OK(sysVeteransCardList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param sysVeterans
    */
	@RequiresPermissions("service:view")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysVeterans sysVeterans) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<SysVeterans> queryWrapper = QueryGenerator.initQueryWrapper(sysVeterans, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<SysVeterans> queryList = sysVeteransService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<SysVeterans> sysVeteransList = new ArrayList<SysVeterans>();
      if(oConvertUtils.isEmpty(selections)) {
          sysVeteransList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          sysVeteransList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<SysVeteransPage> pageList = new ArrayList<SysVeteransPage>();
      for (SysVeterans main : sysVeteransList) {
          SysVeteransPage vo = new SysVeteransPage();
          BeanUtils.copyProperties(main, vo);
          List<SysVeteransCard> sysVeteransCardList = sysVeteransCardService.selectByMainId(main.getId());
          vo.setSysVeteransCardList(sysVeteransCardList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "退役军人信息表列表");
      mv.addObject(NormalExcelConstants.CLASS, SysVeteransPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("退役军人信息表数据", "导出人:"+sysUser.getRealname(), "退役军人信息表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
	@RequiresPermissions("service:view")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response)throws IOException {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		// 错误信息
		List<String> errorMessage = new ArrayList<>();
		int successLines = 0, errorLines = 0;
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(1);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<SysVeterans> list = ExcelImportUtil.importExcel(file.getInputStream(), SysVeterans.class, params);
			  List<SysUser> listSysUsers = ExcelImportUtil.importExcel(file.getInputStream(), SysUser.class, params);
			  for (int i = 0; i < list.size(); i++) {
				  SysVeterans sysVeteransExcel = list.get(i);
				  SysUser sysUserExcel = listSysUsers.get(i);
				  String cardStatus = sysVeteransExcel.getCardStatus();
				  if(StringUtils.isEmpty(cardStatus) || !"正常".equals(cardStatus))continue;
//				  String uname = sysVeteransExcel.getLxfs();
				  String uname = sysVeteransExcel.getSfzh();


				  String rname = sysVeteransExcel.getName();
				  sysUserExcel.setUsername(uname);
//				  String pwd = sysVeteransExcel.getSfzh().substring(12);
				  //优待证号(银行卡号后6位)
				  String pwd = sysVeteransExcel.getYdzh().substring(sysVeteransExcel.getYdzh().length()-6);
				  String Year = sysVeteransExcel.getSfzh().substring(6,10);
				  String Month = sysVeteransExcel.getSfzh().substring(10,12);
				  String Day = sysVeteransExcel.getSfzh().substring(12,14);
				  Date birth = DateUtils.str2Date(Year+"-"+Month+"-"+Day,DateUtils.date_sdf.get());
				  if(0 == Integer.parseInt(sysVeteransExcel.getSfzh().substring(16,17))%2){
					  sysVeteransExcel.setSex("女");
				  }else{
					  sysVeteransExcel.setSex("男");
				  }
				  sysVeteransExcel.setZjlx("身份证");
				  sysVeteransExcel.setAge(DateUtils.getYear() - Integer.parseInt(Year) + 1);
				  sysVeteransExcel.setBirth(birth);
				  sysUserExcel.setBirthday(birth);
				  sysUserExcel.setPassword(pwd);
//				  sysUserExcel.setPhone(uname);
				  sysUserExcel.setRealname(rname);
				  sysUserExcel.setDelFlag(0);
				  sysUserExcel.setStatus(1);
				  String sfzh = sysVeteransExcel.getSfzh();
				  sysUserExcel.setUserNum(sfzh);
				  int sexid =( Integer.parseInt(sysVeteransExcel.getSfzh().substring(16,17)))%2 ;
				  if (sexid ==0)
				  {
				  	sysUserExcel.setSex(2);
				  }
				  else{
					  sysUserExcel.setSex(1);
				  }
				  String salt = oConvertUtils.randomGen(8);
				  sysUserExcel.setSalt(salt);
				  String passwordEncode = PasswordUtil.encrypt(sysUserExcel.getUsername(), sysUserExcel.getPassword(), salt);
				  sysUserExcel.setPassword(passwordEncode);
				  try {
					  sysUserService.saveOrUpdate(sysUserExcel,new UpdateWrapper<SysUser>().lambda().eq(SysUser::getUserNum,sfzh));
					  sysVeteransService.saveOrUpdate(sysVeteransExcel,new UpdateWrapper<SysVeterans>().lambda().eq(SysVeterans::getSfzh,sfzh));
					  successLines++;
				  } catch (Exception e) {
					  errorLines++;
					  String message = e.getMessage().toLowerCase();
					  int lineNumber = i + 1;
					  // 通过索引名判断出错信息
					  if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USERNAME)) {
						  errorMessage.add("第 " + lineNumber + " 行：联系电话已经存在，忽略导入。");
					  } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USER_NUM)) {
						  errorMessage.add("第 " + lineNumber + " 行：身份证号码已经存在，忽略导入。");
					  } else {
						  errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
						  log.error(e.getMessage(), e);
					  }
				  }
				  // 批量将部门和用户信息建立关联关系
				  String departIds = "f7c08cd916e647989b91b8fa55354f51";//用户组ID
				  if (StringUtils.isNotBlank(departIds)) {
					  String userId = sysUserExcel.getId();
					  String[] departIdArray = departIds.split(",");
					  List<SysUserDepart> userDepartList = new ArrayList<>(departIdArray.length);
					  for (String departId : departIdArray) {
						  userDepartList.add(new SysUserDepart(userId, departId));
					  }
					  sysUserDepartService.saveBatch(userDepartList);
				  }
			  }
          } catch (Exception e) {
//			  errorMessage.add("发生异常：" + e.getMessage());
			  log.error(e.getMessage(), e);
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
				  log.error(e.getMessage(), e);
              }
          }
      }
		return ImportExcelUtil.imporReturnRes(errorLines,successLines,errorMessage);
    }

}
